var app = getApp();
var wxCharts = require('../../utils/wxcharts.js');
var common = require('../common/common.js');
var url = app.globalData.url;
var lineChart = null;
var lineChart1 = null;
var lineChart2 = null;
var lineChart3 = null;
var error = common.error;
Page({
  data: {
    navbar: ['今日', '本周', '本月', '本年'],
    currentTab: 0,
    isMainChartDisplay: true,
    operation: '今日经营分析',
    flowData: 0,
    billData: 0,
    riseData: 0,
    active: false,
    //本周店铺数据
    shoplist: [{
      LocName: '上海来福士广场',
      CustTrafficData: {
        IN: "0"
      },
      SalesData: {
        Counts: '0'
      },
      turnover: '0',
      LocId: "SHT2"
    }],
    sortRule: 'asc'  // asc or desc
  },
  navbarTap: function (e) {
    console.log(e)
    var that = this
    that.setData({
      currentTab: e.currentTarget.dataset.idx,
    })
    that.statisticData();
  },
  touchHandler: function (e) {
    console.log(lineChart.getCurrentDataIndex(e));
    lineChart.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ':00' + ' ' + item.name + ':' + item.data
      }
    });
  },
  touchHandler2: function (e) {
    console.log('本周触屏')
    console.log(e)
    console.log(lineChart1.getCurrentDataIndex(e));
    lineChart1.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  touchHandler3: function (e) {
    console.log('本周触屏')
    console.log(e)
    console.log(lineChart2.getCurrentDataIndex(e));
    lineChart2.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  touchHandler4: function (e) {
    console.log('本周触屏')
    console.log(e)
    console.log(lineChart3.getCurrentDataIndex(e));
    lineChart3.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  // 今日
  createSimulationData: function () {
    var categories = [];
    var data = [];
    for (var i = 8; i < 24; i++) {
      //categories.push('2016-' + (i + 1));
      categories.push(i + 1);
      data.push(Math.random() * (20 - 10) + 10);
    }
    // data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  //本周
  createSimulationDataWeek: function () {
    var categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    var data = [];
    return {
      categories: categories,
      data: data
    }
  },
  //本月
  createSimulationDataMonth: function () {
    var categories = [];
    var data = [];
    for (var i = 0; i < 5; i++) {
      categories.push('第' + (i + 1) + '周');
      //categories.push(i + 1);
      data.push(Math.random() * (20 - 10) + 10);
    }
    data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  //本年
  createSimulationDataYear: function () {
    var categories = [];
    var data = [];
    for (var i = 0; i < 4; i++) {
      categories.push('第' + (i + 1) + '季');
      data.push(Math.random() * (20 - 10) + 10);
    }
    return {
      categories: categories,
      data: data
    }
  },
  onReady: function (e) { },
  onLoad: function () {
    var that = this;
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    clearTimeout(timer);
    let timer = setTimeout(() => {
      that.statisticData(); //加载统计数据
    },500)
    
    //that.listShopId();//
  },
  /**
   * 页面加载数据
   * 请求页面时加载:(1)经营分析（2）图表数据（3）店铺列表
   */
  statisticData: function () {
    var that = this;
    var currentTab = that.data.currentTab;
    console.log(currentTab);
    // 页面初始化，接收登录页面所传来的参数
    var user = wx.getStorageSync('account');
    var pwd = wx.getStorageSync('password');
    var Token = wx.getStorageSync('Token');
    var CurentTime = common.CurentTime();
    var locIDs = wx.getStorageSync('dayShopIdStr');
    console.log(locIDs)
    var locIDs2 = wx.getStorageSync('dayShopIdStr2');
    switch (currentTab) {
      case 0:
        that.setData({
          operation: '今日经营分析'
        });
        break;
      case 1:
        that.setData({
          operation: '本周经营分析'
        });
        break;
      case 2:
        that.setData({
          operation: '本月经营分析'
        });
        break;
      case 3:
        that.setData({
          operation: '本年经营分析'
        });
        break;
    }
    that.setData({
      user: user,
      pwd: pwd,
      Token: Token,
      currentTime: CurentTime,
      locIDs: !locIDs ? locIDs2 : locIDs
    });
    //请求摘要数据
    var params = {
      Token: Token,
      Type: currentTab,
      WithSalesData: true,
      WithComparedData: true,
      LocationIDs: locIDs
    }
    that.statis(url, params); //（1）请求统计数据
    that.listShopId(url,params);
    that.listshopData(params) //请求店铺列表
    that.chartData(params, currentTab) //请求图表数据  
  },
  onShareAppMessage: function (e) {
    return {
      title: '',
      path: '/page/user?id=123' //（路径，即是你在app.json中注册的路径，每个页面均需要填写这个，才会出现分享?id= 123为参数部分）
    }
  },
  onShow: function () {
    var that = this;
    that.statisticData(); //加载统计数据
  },
  onPullDownRefresh() {
    let that = this;
    wx.showNavigationBarLoading();
    wx.stopPullDownRefresh();
    setTimeout(() => {
      that.statisticData(); //加载统计数据
      
      wx.showNavigationBarLoading();
    }, 3000)
  },
  /**
   * 加载搜索页面数据
   * 默认加载全部店铺
   */
  listShopId: function (url, params){
    var that = this;
    common.requestLoading(url + '/shops', params, '正在加载中', function (res) {
      var listShopId = [];
      for(let item of res){
        console.log(item)
        listShopId.push(item.LocationID); 
      }
      console.log(listShopId);
      var dayShopIdStr2 = listShopId.join("|");
      wx.setStorageSync("dayShopIdStr2", dayShopIdStr2);
    },error)
  },
  /* */
  /**
   * 统计数据请求 
   */
  statis: function (url, params) {
    var that = this;
    common.requestLoading(url + '/sumdata', params, '正在加载数据', function (res) {
      //res就是我们请求接口返回的数据
      console.log(res)
      var SumData = res.SumData
      var countsData = SumData.CustTrafficData.Basic.IN //客流量
      var serviceData = SumData.StaffData.Basic //服务人员
      var sales = SumData.SalesData.Basic.Counts //开单数
      var countsCom = SumData.CustTrafficData.Compared.IN //比较客流量
      var serviceCom = SumData.StaffData.Compared //比较服务人员
      var salesCom = SumData.SalesData.Basic.Amt //比较开单数

      var serviceRateData = Math.ceil(countsData / serviceData) //同期服务率
      var serviceRateDataCom = Math.ceil(countsCom / serviceCom) //比较服务率
      var dealRate = parseFloat(sales / countsData).toFixed(2) //同期成交率
      var dealRateCom = Math.ceil(salesCom / countsCom) //比较成交率

      /*
       *判断非空、未定义、null 
       */
      function dataNull(data) {
        if (isNaN(data)) {
          data = 0
        }
        return data
      }
      //相对应的值转化
      countsData = dataNull(countsData)
      sales = dataNull(sales)
      dealRate = dataNull(dealRate)
      /**
       * 增长率
       */
      var countsRate = common.compareVal(countsData, countsCom) //客流量增长率
      var serveRate = common.compareVal(serviceRateData, serviceRateDataCom) //服务率增长率
      var billingsRate = common.compareVal(sales, salesCom) //开单数增长率
      var dealsRate = common.compareVal(dealRate, dealRateCom) //成交率增长率
      that.setData({
        flowData: common.format_number(countsData), //客流量
        billData: common.format_number(sales), //开单数
        riseData: dealRate, //成交率
      })
    }, error)
  },
  /**
   * 图表数据请求
   */
  chartData: function (params, currentTab) {
    var that = this
    common.requestLoading(url + '/data', params, '正在加载数据', function (res) {
      console.log(res)
      var basic = res.BasicData;
      var counts = basic.CustTrafficData; //客流量
      var sales = basic.SalesData; // 下单数
      var WCustTrafficArr = [];
      var WcountsArr = [];
      var windowWidth = 320;
      try {
        var res = wx.getSystemInfoSync();
        windowWidth = res.windowWidth;
      } catch (e) {
        console.error('getSystemInfoSync failed!');
      }

      function timesDataKey(times, counts, WCustTrafficArr, sales) {
        for (var i = 0; i < counts.length; i++) {
          var lab = counts[i].LABEL;
          var n = times.indexOf(lab);
          WCustTrafficArr[n] = counts[i].IN; //客流量

        }
        for (var j = 0; j < sales.length; j++) {
          var saleTime = sales[j].LABEL;
          var time = times.indexOf(saleTime);
          WcountsArr[time] = sales[j].Counts; //下单数
        }
      }
      switch (currentTab) {
        case 0:
          var Arr = ['09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'];
          var simulationData = that.createSimulationData().categories;
          timesDataKey(Arr, counts, WCustTrafficArr, sales);
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          console.log(WcountsArr)
          lineChart = that.Chart('lineCanvas', simulationData, WCustTrafficArr, WcountsArr, windowWidth);
          break;
        case 1:
          var dateArr = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']; //本周
          var simulationData1 = that.createSimulationDataWeek().categories;
          timesDataKey(dateArr, counts, WCustTrafficArr, sales)
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          lineChart1 = that.Chart('lineCanvas1', simulationData1, WCustTrafficArr, WcountsArr, windowWidth);
          break;
        case 2:
          var weekArr = ['1', '2', '3', '4', '5']; //本月核对
          var simulationData2 = that.createSimulationDataMonth().categories;
          timesDataKey(weekArr, counts, WCustTrafficArr, sales)
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          lineChart2 = that.Chart('lineCanvas2', simulationData2, WCustTrafficArr, WcountsArr, windowWidth);
          break;
        case 3:
          var yearArr = ['1', '2', '3', '4'];
          var simulationData3 = that.createSimulationDataYear().categories;
          timesDataKey(yearArr, counts, WCustTrafficArr, sales)
          common.calUndefined(WCustTrafficArr);
          common.calUndefined(WcountsArr);
          lineChart3 = that.Chart('lineCanvas3', simulationData3, WCustTrafficArr, WcountsArr, windowWidth);
          break;
      }
    }, error)

  },
  /**
   * 店铺列表数据
   */
  listshopData: function (params) {
    var that = this;
    common.requestLoading(url + '/listdata', params, '正在加载中', function (res) {
      console.log(res)
      var newres = res;
      for (var i = 0; i < res.length; i++) {
        var salesCounts = res[i].SalesData.Counts
        console.log(salesCounts)
        console.log(isNaN(parseFloat(salesCounts)))
        if (isNaN(parseFloat(salesCounts))) {
          salesCounts = 0
        }
        newres[i].SalesData.Counts = salesCounts
      }
      // that.flowOnClick(newres)
      //that.sortReduce(newres, 'CustTrafficData')

      that.setData({
        shoplist: newres
      })
    }, error)

  },
  /**
   * 点击客流量
   */
  flowOnClick(newres) {
    var that = this;
    var nowNum = that.data.currentTab;
    console.log(nowNum)
    if (nowNum === 0){

      that.setData({
        active: true
      })
    }
    console.log(that.data.active);
    let type = that.data.sortRule == 'asc' ? 'desc' : 'asc'
    that.setData({
      sortRule: type
    })
    let res = that.sortReduce(that.data.shoplist, 'CustTrafficData', type);

    that.setData({
      shoplist: res
    })
  },
  /**
   * 提示功能（提示当前时间无数据）
   * 提示客流量并且开单数无数据的话，会出现提示：
   */
  showModeTime: function (e) {
    wx.showModal({
      title: '提示',
      content: '当前时间暂无数据信息，请稍后重试！',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   *减少 
   */
  sortReduce(arr, key, sort) {
    console.log(sort)
    return arr.sort(function (a, b) {
      var x = Number(a[key].IN);
      var y = Number(b[key].IN);
      if (typeof x === "string" && typeof y === "string") {
        x = x.toUpperCase();
        y = y.toUpperCase();
      }
      if (sort == 'desc') {
        return ((x > y) ? -1 : ((x < y) ? 1 : 0))
      } else {
        return ((x < y) ? -1 : ((x > y) ? 1 : 0))
      }
    })
  },
  /**
   * 例如chart1图表数据，chart2图表数据
   * 图表填充数据
   */
  Chart: function (canvasId, categories, WCustTrafficArr, WcountsArr, windowWidth) {
    return new wxCharts({
      canvasId: canvasId,
      type: 'line',
      categories: categories,
      animation: true,
      dataLabel: true,
      // background: '#f5f5f5',
      series: [{
        name: '客流量',
        //data: simulationData.data,
        data: !WCustTrafficArr.length ? this.showModeTime() : WCustTrafficArr,
        //dataLabel: true,
        format: function (val, name) {
          return val;
        }
      },
      {
        name: '开单数',
        data: !WcountsArr.length ? new Array(WCustTrafficArr.length).fill(0) : WcountsArr,
        format: function (val, name) {
          return val;
        }
      },
      
      /* {
        name: '成交率(%)',
        data: rate,
        format: function (val, name) {
          return val;
        }
      } */
      ],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        // title: '成交金额 (万元)',
        format: function (val) {
          return val.toFixed(2);
        },
        min: 0,
        disabled: true
      },
      width: windowWidth,
      height: 260,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });
  },

});